google.load("jquery", "1");
var map,geocoder,startField1,lat1,lng1,autocomplete1;
var HOME_DEFAULT = new google.maps.LatLng(1.358798,103.963591);
var ZOOM_DEFAULT = 10;
var markersArray = [];


google.setOnLoadCallback(function() {
	geocoder = new google.maps.Geocoder();
	startField1 = document.getElementById('startField1');
	lat1 = document.getElementById('lat1');
	lng1 = document.getElementById('lng1');
	var mapOptions = {
		center: HOME_DEFAULT,
		zoom: ZOOM_DEFAULT,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById('map'), mapOptions);
	autocomplete1 = new google.maps.places.Autocomplete(startField1);
	autocomplete1.bindTo('bounds', map);


	google.maps.event.addListener(autocomplete1, 'place_changed', function() {
		showPlace(autocomplete1.getPlace().geometry.location);
	});
	
	google.maps.event.addListener(map, 'click', function(event) {
		putMarker(event.latLng);
	});
});
function showPlace(location) {
	putMarker(location);
	map.setCenter(location);
	map.setZoom(15);
}
function putMarker(location) {
	lat1.value = location.lat();
	lng1.value = location.lng();
	deleteOverlays();
	var marker = new google.maps.Marker({
		position: location,
		map: map
	});
	markersArray.push(marker);
}
function deleteOverlays() {
	if (markersArray) {
		for (i in markersArray) {
			markersArray[i].setMap(null);
		}
		markersArray.length = 0;
	}
}



function submitToFT() {
	$('#message').html("Called submitToFT")
	var daysChecked = new Array();
	$('#inputs input:checked').each(function() {
		daysChecked.push($(this).attr('id'));
	});
	var m = daysChecked.join('|');
	var dataString = "sql=INSERT INTO 1alijL-Ib3_Mjiash2A8tcJosG0eljkT0mNBXNd8 (Name,Category,Address,Latitude,Longitude,OpenTime,CloseTime,DaysOfWeek) VALUES ('"
		+ $('#nam1').val() + "','" + $('#cat1').val() + "','" + $('#startField1').val() + "',"
		+ $('#lat1').val() + "," + $('#lng1').val() + ",'" + $('#opn1').val() + "','" + $('#cls1').val() + "','" + m
		+ "')&key=AIzaSyAdknM5MFaotgggSTAAPEU7WezHoENIv9U";
	console.log('Postong: ' + dataString);
	//alert (dataString);return false;
	$.ajax({
		type: "POST",
		url: "https://www.googleapis.com/fusiontables/v1/query",
		data: dataString,
		success: function() {
			$('#message').html("<h2>Service details Submitted!</h2>").hide().fadeIn(1500);
		},
		error: function(xhRequest, ErrorText, thrownError) {
			$('#message').html("<h2>Request FAILED</h2>. " + ErrorText);
		}
	});
	return false;
}